/**
 * 
 */
package edu.kit.csl.cratylus.extraction.elki;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

import de.lmu.ifi.dbs.elki.datasource.bundle.BundleMeta;
import de.lmu.ifi.dbs.elki.datasource.parser.AbstractParser;
import de.lmu.ifi.dbs.elki.datasource.parser.AbstractStreamingParser;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;

/**
 * @author felix
 * 
 */
public class StringParser extends AbstractStreamingParser {

	private BufferedReader reader;
	protected int lineNumber;
	protected BundleMeta meta = null;
	Event nextevent = null;
	private static final Logging LOG = Logging.getLogger(StringParser.class);
	protected String curString = null;

	public StringParser(Pattern colSep, char quoteChar) {
		super(colSep, quoteChar);
		// TODO Auto-generated constructor stub
		meta = new BundleMeta(0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.lmu.ifi.dbs.elki.datasource.parser.StreamingParser#initStream(java
	 * .io.InputStream)
	 */
	@Override
	public void initStream(InputStream in) {
		// TODO Auto-generated method stub
		reader = new BufferedReader(new InputStreamReader(in));
		lineNumber = 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.lmu.ifi.dbs.elki.datasource.bundle.BundleStreamSource#getMeta()
	 */
	@Override
	public BundleMeta getMeta() {
		return meta;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.lmu.ifi.dbs.elki.datasource.bundle.BundleStreamSource#data(int)
	 */
	@Override
	public Object data(int rnum) {
		if (rnum == 0) {
			return curString;
		}
		throw new ArrayIndexOutOfBoundsException();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.lmu.ifi.dbs.elki.datasource.bundle.BundleStreamSource#nextEvent()
	 */
	@Override
	public Event nextEvent() {
		if (nextevent != null) {
			Event ret = nextevent;
			nextevent = null;
			return ret;
		}
		try {
			for (String line; (line = reader.readLine()) != null; lineNumber++) {
				if (!line.startsWith(COMMENT) && line.length() > 0) {
					curString = line.trim();
					return Event.NEXT_OBJECT;
				}
			}
			reader.close();
			reader = null;
			return Event.END_OF_STREAM;
		} catch (IOException e) {
			throw new IllegalArgumentException("Error while parsing line "
					+ lineNumber + ".");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.lmu.ifi.dbs.elki.datasource.parser.AbstractParser#getLogger()
	 */
	@Override
	protected Logging getLogger() {
		return LOG;
	}

	/**
	 * Parameterization class.
	 * 
	 * @author Erich Schubert
	 * 
	 * @apiviz.exclude
	 */
	public static class Parameterizer extends AbstractParser.Parameterizer {

		@Override
		protected void makeOptions(Parameterization config) {
			super.makeOptions(config);
		}

		@Override
		protected StringParser makeInstance() {
			return new StringParser(colSep, quoteChar);
		}
	}
}
